﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Company.Web.Infrastructure
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class ValidateDateRangeAttribute : ValidationAttribute 
    {
        private const string _defaultErrorMessage = "'{0}' debe ser menor que '{1}'.";
        private readonly object _typeId = new object();

        public ValidateDateRangeAttribute(string DateFromProperty, string DateToProperty)
            : base(_defaultErrorMessage)
        {
            m_DateFrom = DateFromProperty;
            m_DateTo = DateToProperty;
        }

        public string m_DateTo { get; private set; }
        public string m_DateFrom { get; private set; }

        public override object TypeId
        {
            get
            {
                return _typeId;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,m_DateFrom, m_DateTo);
        }

        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object From = properties.Find(m_DateFrom, true /* ignoreCase */).GetValue(value);
            object To = properties.Find(m_DateTo, true /* ignoreCase */).GetValue(value);
            try
            {
                DateTime a = Convert.ToDateTime(From);
                DateTime b = Convert.ToDateTime(To);
                if (a <= b)
                    return true;
            }
            catch (Exception)
            {
                return false;
            }
            return false;
        }
    }
}
